const pool = require('../conf/db')

// 获取所有驻商单位
const getAllBusinesses = async () => {
  const connection = await pool.getConnection()
  try {
    const [rows] = await connection.query('SELECT * FROM business')
    return rows
  } catch (err) {
    throw new Error('无法获取驻商单位' + err)
  } finally {
    connection.release()
  }
}

// 创建新驻商单位
const createBusiness = async (params) => {
  const connection = await pool.getConnection()
  try {
    const { name } = params
    const [exist] = await connection.query('SELECT * FROM business WHERE name =?', [name])
    if (exist.length > 0) {
      throw new Error('驻商单位已存在')
    }
    await connection.execute('INSERT INTO business (name) VALUES (?)', [name])
    const [result] = await connection.query('SELECT * FROM business WHERE id = LAST_INSERT_ID()')
    return result[0]
  } catch (err) {
    throw new Error('新增驻商单位失败：' + err.message)
  } finally {
    connection.release()
  }
}
module.exports = {
  getAllBusinesses,
  createBusiness
}
